package com.cat.cdd.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cat.cdd.dto.Result;
import com.cat.cdd.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.cat.cdd.utils.constants.RedisConstants.*;
import static com.cat.cdd.utils.constants.RedisConstants.CACHE_SHOP_KEY;

/**
 * @Author 猫大仙
 */
@Slf4j
@Component
public class CacheClient {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public void set(String key, Object value,Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    public void setWithLogicalExpire(String key, Object value,Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }


    /**
     * 缓存穿透解决方案
     * @param id
     * @return
     */
    public <R,ID> R queryWithPassThrough(
            String keyPre, ID id, Class<R> type, Function<ID,R> DBFallBack
            ,Long time, TimeUnit unit) {
        String key = keyPre + id;
        //从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json,type);
        }
        //判断是否是空字符串
        if(json != null){
            return null;
        }
        //不存在，根据id查询数据库
        R r = DBFallBack.apply(id);
        if(r == null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //写入redis
        this.set(key,r,time,unit);
        return r;
    }



    /**
     * 缓存击穿解决方案   逻辑过期解决
     * @param id
     * @return
     */
    private static final ExecutorService CacheBuilder = Executors.newFixedThreadPool(10);
    public  <R,ID> R queryWithLogicalExpire(
            String keyPre, ID id,  Class<R> type,Function<ID,R> DBFallBack
            ,Long time, TimeUnit unit) {
        String key = keyPre + id;
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            //存在
            return null;
        }
        //将json转为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if(expireTime != null && expireTime.isAfter(LocalDateTime.now())){
            //未过期,直接返回店铺信息
            return r;
        }
        //过期,则开启独立线程，实现缓存重建
        //缓存重建
        //获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean isLock = tryLock(lockKey);
        //判断是否获取锁成功
        if(isLock){
            if(expireTime != null && expireTime.isAfter(LocalDateTime.now())){
                //未过期,直接返回店铺信息
                return r;
            }
            //成功,创建一个线程，实现缓存重建
            CacheBuilder.submit(() -> {
                try {
                    R apply = DBFallBack.apply(id);
                    this.setWithLogicalExpire(key, apply, time, unit);
                } catch (Exception e) {
                    //失败,返回过期信息
                    throw new RuntimeException(e);
                }
                //释放锁
                unLock(lockKey);
            });
        }

        return r;
    }

    private Boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
